var calendar = null;

$(function () {
    $(".tpv-nav-item:first").addClass("active");
    var options = {
		events_source: 'meeting/event/' + $(".tpv-nav-item:first").val(),
		view: 'month',
		tmpl_path: 'tmpls/',
		tmpl_cache: false,
		modal: "#event-detail",
		modal_type: "ajax",
		onAfterEventsLoad: function(events) {
			if(!events) {
				return;
			}
//			var list = $('#eventlist');
//
//			list.html('');
//
//			$.each(events, function(key, val) {
//				$(document.createElement('li'))
//					.html('<a href="' + val.url + '">' + val.title + '</a>')
//					.appendTo(list);
//			});
		},
		onAfterViewLoad: function(view) {
			// chaohung , 20190111 , get today(start)
			var today1 = new Date().toLocaleDateString();
			var reg = new RegExp("/","g");
			var today = today1.replace(reg,"-");
			// chaohung , 20190111 , get today (end)			
			//console.log('onAfterViewLoad');
			$('.btn-group button').removeClass('active');
			$('button[data-calendar-view="' + view + '"]').addClass('active');
            $('h3.page-header').text(this.getTitle());

            $(".events-list a[data-toggle='tooltip']").each(function() {
                var width = $(this).closest(".cal-month-day").width() - 10;
                $(this).css({width: width + 'px'});
            });
            
            /* chaohung , 20190109 , add click for meeting , Hour , (start)*/
            $('.j-cal-hour').click(function(){
            	var bookinghour = $(this).attr('data-cal-hour');
            	//alert(bookinghour);            	
            	var bookingroomId = $('.tpv-nav-item.active').val();
            	var bookingroomText = $('.tpv-nav-item.active').text();
            	// chaohung , 20190122 , add data information , fix add meeting error 
            	var bookingday = $(this).attr('data-cal-date');
            	openCreateMeetingModal_hour(bookingroomId,bookingroomText,bookinghour,bookingday);
            	
            	return false;
            });
            /* chaohung , 20190109 , add click for meeting , Hour , (end)*/
            /* chaohung , 20190109 , add click for meeting , Month , (start)*/
            $('.j-cal-month ').click(function(){
            	var bookingday = $(this).find('span').attr('data-cal-date');
        		            	
            	var bookingroomId = $('.tpv-nav-item.active').val();
            	var bookingroomText = $('.tpv-nav-item.active').text();
            	openCreateMeetingModal_month(bookingroomId,bookingroomText,bookingday); 
        		return false;
        	});
            /* chaohung , 20190109 , add click for meeting , Month , (end)*/
            /* chaohung , 20190119 , add click for meeting , Week , (start)*/
            $('.j-cal-week').click(function(){
            	var bookingday = $(this).attr('data-cal-date');
        		         	
            	var bookingroomId = $('.tpv-nav-item.active').val();
            	var bookingroomText = $('.tpv-nav-item.active').text();
            	openCreateMeetingModal_month(bookingroomId,bookingroomText,bookingday); 
        		return false;
        	});
            /* chaohung , 20190119 , add click for meeting , Week , (end)*/
            
            //$("#dateInput .form-control").datetimepicker('update', moment(this.options.position.start.getTime() / 1000, "X").format(systemDateFormat));
            /*$("#dateInput").datetimepicker({
            	maxDate : moment(),
            	showWeekNumbers : true,
            	timePicker : false,
            	timePicker12Hour : false,
            	format: 'YYYY-MM-DD'
            });*/
		},
		onAfterModalShown: function(events){
		         initClipboard();
		},
		onAfterModalHidden: function(events){
              destroyClipboard();
		},
		classes: {
			months: {
				general: 'label'
			}
		}
	};

	calendar = $('#calendar').calendar(options);

    $(".tpv-nav-item").click(function() {
        if(!$(this).hasClass("active")) {
            $(".tpv-nav-item.active").removeClass("active");
            $(this).addClass("active");
            calendar.setOptions({
                events_source: 'meeting/event/' + $(this).val(),
                onAfterModalShown: function(events){
                    initClipboard();
                },
                onAfterModalHidden: function(events){
                    destroyClipboard();
                }
            });
            calendar.view();
        }
    });

	if(LANGUAGE_CODE == 'zh_CN') {
	    calendar.setLanguage('zh-CN');
	    calendar.view();
	}

    $('.btn-group button[data-calendar-view]').each(function() {
        var $this = $(this);
        $this.click(function() {
            calendar.view($this.data('calendar-view'));
        });
    });

	$('.btn-group button[data-calendar-nav]').each(function() {
		var $this = $(this);
		$this.click(function() {
			calendar.navigate($this.data('calendar-nav'));
		});
	});

	$("#event-detail .btn-close").click(function() {
        $MB.closeModal("event-detail");
	});
	
	// chaohung , 20190123 , using datetimepicker to choose date
	var date = new Date();
	$('#dateInput').datetimepicker({
		format: 'yyyy-mm-dd hh:ii',
		autoclose: true,
		minView: 2,
		startDate: date,
		todayHighlight: true
	}).on('change',function() {	
		var chooseday = $("#dateInput .form-control").val();
		var calendartimeformat = moment(chooseday, 'YYYY-MM-DD HH:mm' );
		calendar.navigate("date", calendartimeformat);
	});

});

var handle = false;

 function joinMeeting(moderator, meetingId, userId, username) {
    if(!handle) {
        handle = true;
    } else {
        return;
    }

    var data = {"moderator" : moderator};
    $.ajax({
        type : "post",
        url : "/meeting/join/" + meetingId,
        cache : false,
        async: false,
        data: data,
        success : function(r) {
            if(r.code == 0) {
                window.open(r.msg.url, '_blank').location;
            } else {
                if(r.code == 609) {//locked
                   $MB.closeModal('event-detail');
                   showMeetingLock(meetingId, 'user-' + userId, username);
                } else {
                   $MB.n_danger($MB.i18n(r.msg));
                }
            }
            handle = false;
        },
        error: function() {
            handle = false;
        }
    });
 }

 var clipboard;

 function initClipboard(){
     clipboard = new ClipboardJS('.copyBtn', {
         container: document.getElementById('event-detail')
     });
     clipboard.on('success', function(e) {
          $MB.n_success($MB.i18n('meeting.copy.successtxt'));
     });
     clipboard.on('error', function(e) {
         $MB.n_danger($MB.i18n('meeting.copy.failtxt'));
     });
 }

 function destroyClipboard(){
   if(clipboard){
     clipboard.destroy();
   }
 }

 function copyMeetingTxt(e){
   $MB.closeModal(e.attr('id'));
   var meetingId=e.find("input[name='meeting-id']").val();
   openInviteTxt(meetingId);
 }
 
 /*******
  * Tpv zhongxiang.huang 20181226--add by zhongxiang.huang,meeting invite----start
  * *******/
 function wechartInviteMetting(e){
     $MB.closeModal(e.attr('id'));
     var meetingId=e.find("input[name='meeting-id']").val();
     openInviteWechart(meetingId);
 }

 function emailInviteMetting(e){
     $MB.closeModal(e.attr('id'));
     // Add by ken.he on 20190117 ---start---
     var meetingId=e.find("input[name='meeting-id']").val();
     $.post(ctx + "smtp/sendmail", {"meetingId": meetingId }, function(r){
 		console.log(r);
 		if (r.code === 0) {
//             $MB.n_success($MB.i18n('email.send.success'));
         } else if(r.code === 1){
         	$MB.n_danger($MB.i18n('email.failtxt.configs.error'));
         } else if(r.code === 2){
         	$MB.n_danger($MB.i18n('email.failtxt.address.error'));
         } else if(r.code === -1){
         	$MB.n_danger($MB.i18n('email.failtxt.configs.off'));
         } else if(r.code === -2){
         	$MB.n_danger(r.msg);
         }else {
             $MB.n_danger(r.msg);
         }
 	});
     // Add by ken.he on 20190117 ---end---
 }

 /*******
  * Tpv zhongxiang.huang 20181226--add by zhongxiang.huang,meeting invite----end
  * *******/
 
 /*******
  * chaohung 20190111--add meeting ----start
  * *******/
 function openCreateMeetingModal_hour(meetingRoomId,meetingRoomName,bookinghour,today){
	 //alert("bookingroomId : " + bookingroomId + " , bookingroomText : " + bookingroomText + " , bookinghour : " + bookinghour);
	 	var meetingRoomId = meetingRoomId;
	    var $form = $('#meeting-add');
	    $form.modal();
	    $form.find('#repeat-off').iCheck('check');
	    $form.find("#meeting-add-form").attr("action", "add");
	    $form.find("#select-room").hide();
	    $form.find("#is-room").css('display','inline');
	    $form.find("input[name='meetingroomName']").val(meetingRoomName);
	    $form.find("input[name='meetingroomId']").val(meetingRoomId);

	    // setting Default date and duration(start)
	    $form.find('#meeting-date').val(today);
	    $form.find('#meeting-date-link').val(today);
	    $form.find('#meeting-time').val(bookinghour);
	    $form.find('#meeting-time-link').val(bookinghour);
	    
	    $form.find('#duration-2').attr("selected","selected");
	    // setting Default date and duration(end)
 }
  
 function booking(){
	 
	var today1 = new Date().toLocaleDateString();

	var reg = new RegExp("/","g");
	var bookingday = today1.replace(reg,"-");
	 	
	var bookingroomId = $('.tpv-nav-item.active').val();
    	var bookingroomText = $('.tpv-nav-item.active').text();
 	openCreateMeetingModal_month(bookingroomId,bookingroomText,bookingday);
	 
 }
 
 function openCreateMeetingModal_month(meetingRoomId,meetingRoomName,bookingday) {
	    var meetingRoomId = meetingRoomId;
	    var $form = $('#meeting-add');
	    $form.modal();
	    $form.find('#repeat-off').iCheck('check');
	    $form.find("#meeting-add-form").attr("action", "add");
	    $form.find("#select-room").hide();
	    $form.find("#is-room").css('display','inline');
	    $form.find("input[name='meetingroomName']").val(meetingRoomName);
	    $form.find("input[name='meetingroomId']").val(meetingRoomId);
 
	    $form.find('#meeting-list-setting-mute').iCheck('check');
	    $form.find('#meeting-list-setting-noname').iCheck('check');

	    $form.find('#meeting-list-setting-recorder').iCheck('check');   
	    $form.find('#meeting-setting-autorecorder-manu').iCheck('check');
	    
	    // setting Default date and duration(start)
	    $form.find('#meeting-date').val(bookingday);
	    $form.find('#meeting-date-link').val(bookingday);
	    $form.find('#meeting-time').val("09:00");	    
	    $form.find('#meeting-time-link').val("09:00");
	    $form.find('#duration-4').attr("selected","selected");
	    // setting Default date and duration(end)	    	  
}
 
 /*******
  * chaohung 20190109--add meeting ----end
  * *******/